package com.lin.forum.config;

import com.lin.forum.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//拦截器
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Value("${lin-forum.login.url}")
    private String defaultURL;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证token是否合法
        String userToken=request.getHeader("user_token");
        if(!defaultURL.startsWith("/")){
            defaultURL="/"+defaultURL;
        }
        if(userToken==null){
            response.sendRedirect(defaultURL);
            return false;
        }
        log.info("在LoginInterceptor，preHandle方法中，从header中获取信息，token:"+userToken);
        Claims claims= JwtUtils.verify(userToken);
        if(claims==null){
            response.setStatus(401);
            return false;
        }

        return true;
    }
}
